!pr2
Short Integer Square Root Subroutine.......Bob Sander-Cederlof

In some graphics situations you need a square root subroutine (it is probably the fault of Pythagoras).   Since the screen coordinates are integers, a short and fast integer square root subroutine can be handy.

The following program is probably not in the "fast" category, but it is indeed short.  It can produce the integer value of the square root of any integer from 0 through 65535.  The program uses the method of subtracting successive odd numbers.

Every perfect square (N*N, where N is an integer) is the sum of a series of odd numbers from 1 through 2*N-1.  Thus 4=1+3, 25=1+3+5+7+9, etc.

The program starts by subtracting 1, then 3, then 5, and so on until the remainder is negative.  When the remainder goes negative, the last odd number subtracted was 2*N+1, so we can get the square root by dividing that odd number by 2.

I set up the routine so I could test it with an Applesoft pro- gram.  You can POKE the low 8-bits of a number at 768 ($300), the high 8-bits at 769, and CALL 772.  Upon return, PEEK(770)+ 256*PEEK(771) gives you the integer value of the square root.

I used a couple of tricks in the code.  For one, the variable ODD is always an even number.  Since I preface the subtraction with CLC, a "borrow" is assumed, so it has the effect of sub- tracting the odd number which is one larger than the even number in ODD.  This save a LDA #1 instruction after line 1090.

In lines 1190-1230, I add 2 to the even number in ODD.  But you can see that line 1200 is ADC #1.  This adds 2 because carry happens to be set.
